package com.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

public class FileManager {
	// 파일 다운로드 메소드
	public static boolean doFileDownload(HttpServletResponse resp,
			String saveFileName, String originalFileName, String path) {
		try {
			String filePath = path + File.separator + saveFileName;
			if (originalFileName == null || originalFileName.equals("")) {
				originalFileName = saveFileName;
			}
			
			originalFileName = new String(originalFileName.getBytes("euc-kr"),"iso-8859-1");
			
			File f = new File(filePath);
			if (!f.exists()) {
				return false;
			}
			
			resp.setContentType("application/octet-stream");
			resp.setHeader("Content-disposition", "attachment;filename="+originalFileName);
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
			OutputStream out = resp.getOutputStream();
			int n;
			byte bytes[] = new byte[4096];
			while ((n = bis.read(bytes,0,4096))!=-1) {
				out.write(bytes,0,n);
			}
			out.flush();
			out.close();
			bis.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public static void doFileDelete(String fileName, String path){
		try {
			String filePath = path + File.separator + fileName;
			File f = new File(filePath);
			if (f.exists()) {
				f.delete();
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
